<!-- 编辑弹窗 -->
<template>
    <div class="ele-body">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
        <el-card  >  
          <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
            <div style="width: 50%;" >基础信息</div>
            <div style="width: 50%;display: flex;justify-content:end;" >
              <div v-show="form.checkNo!='' && form.checkNo!=null" style="width: 30%;color:var(--color-primary)" >盘点单号:{{ form.checkNo }}</div>
            </div>
          </div>      
          <el-row :gutter="24">
            <el-col :md="6" :sm="24" >
              <el-form-item label="制单日期:"  prop="createDate">
                <el-date-picker v-model="form.createDate" type="date" placeholder="请输入制单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="24">
              <el-form-item label="制单人:" prop="createUser">
                <el-select  v-model="form.createUser" filterable placeholder="请选择制单人" style="width:100%"  >
                  <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="24">
              <el-form-item label="盘点仓库:" prop="wareHouseId">
                <el-select  v-model="form.wareHouseId" filterable placeholder="请选择盘点仓库" style="width:100%" >
                  <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="24">
              <el-form-item label="盘点类型:" prop="checkTypeId">
                <el-select  v-model="form.checkTypeId" filterable placeholder="请选择盘点类型" style="width:100%"  >
                  <el-option  v-for="item in checkTypeDicts" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :md="6" :sm="24" >
              <el-form-item label="库存金额:"  >
                <el-input v-model="form.sumStockAmount" disabled />
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="24" >
              <el-form-item label="盘点金额:"  >
                <el-input v-model="form.sumCheckAmount" disabled />
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="24" >
              <el-form-item label="差异金额:"  >
                <el-input v-model="form.sumDiffAmount"   disabled/>
              </el-form-item>
            </el-col> -->
            <el-col :md="24" :sm="24" >
              <el-form-item label="备注:"  >
                <el-input :rows="2"
                    clearable
                    type="textarea"
                    :maxlength="200"
                    v-model="form.remark"
                    placeholder="请输入备注说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card  style="margin-top: 10px">
          <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
            <div style="width: 8%;" >产品列表</div>
            <div style="width: 92%;display: flex;justify-content:start;" >
              <div style="width: 100%;color:var(--color-primary)" > 
                  <el-button type="primary" class="ele-btn-icon" icon="el-icon-plus"  style="width: 10%;" @click="OpenProductList" v-permission="'Inventory_Checkorder_ProductAdd'"   >选择产品 </el-button>
                </div>
            </div>
          </div> 
          <el-table :data="form.items" ref="items"  :border="true" style="width: 100%"  :height="tableHeight" :full-height="tableFullHeight" show-summary :summary-method="getSummaries"  :cell-style="cellStyle">
            <el-table-column type="index" width="50" align="center" label="序号"  fixed='left' />
            <el-table-column label="产品编号" width="150" prop="productCode" sortable  align="center">
                <template slot-scope="{ row }">
                  <el-form-item label-width="10" style="margin-bottom:0;" >
                    <span>{{ row.productCode }}</span>
                  </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="产品名称" width="150" prop="productName" sortable  align="center">
                <template slot-scope="{ row }">
                  <el-form-item label-width="10" style="margin-bottom:0;" >
                    <span>{{ row.productName }}</span>
                  </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="规格" align="center" prop="spc" sortable width="100" >
              <template slot-scope="{ row }">
                <span>{{ row.spc }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unitDesc" sortable width="100">
                <template slot-scope="{ row }">
                    <span>{{ row.unitDesc }}</span>
                </template>
            </el-table-column>
            <el-table-column label="实际库存" align="center" prop="stockQty" sortable width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.stockQty }}</span>
                    <!-- <el-input  v-model="row.stockQty"  disabled /> -->
                </template>
            </el-table-column>
            <el-table-column label="盘点数量" align="center" prop="checkQty" sortable width="100">
              <template slot-scope="{ row ,$index}">
                <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.checkQty'" :rules="itemRules.qty" >
                  <el-input  v-model="row.checkQty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.checkQty = row.checkQty.replace(/[^\d.]/g,'');
                    row.checkQty = row.checkQty.replace(/\.{2,}/g,'.');
                    row.checkQty = row.checkQty.replace(/^\./g,'');
                    row.checkQty = row.checkQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.checkQty = row.checkQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="差异数量" align="center" prop="diffQty" sortable width="100">
              <template slot-scope="{ row }">
                <span>{{ row.diffQty }}</span>
              </template>
            </el-table-column>
            <el-table-column label="成本单价(元)" align="center" prop="costPrice" sortable width="150">
                <template slot-scope="{ row ,$index}">
                  <!-- <span>{{ row.costPrice }}</span> -->
                  <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.costPrice'" :rules="itemRules.costPrice" >
                    <!-- <el-input  v-model="row.costPrice"   prefix-icon="el-icon-_rmb" /> -->

                    <el-input  v-model="row.costPrice"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.costPrice = row.costPrice.replace(/[^\d.]/g,'');
                    row.costPrice = row.costPrice.replace(/\.{2,}/g,'.');
                    row.costPrice = row.costPrice.replace(/^\./g,'');
                    row.costPrice = row.costPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.costPrice = row.costPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" prefix-icon="el-icon-_rmb" />
                  </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="库存金额" align="center" prop="stockAmount" sortable width="120">
              <template slot-scope="{ row }">
                <span>{{ row.stockAmount }}</span>
                <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-input  v-model="row.stockAmount"  prefix-icon="el-icon-_rmb" disabled />
                </el-form-item> -->
              </template>
            </el-table-column>
            <el-table-column label="盘点金额" align="center" prop="checkAmount" sortable width="120">
              <template slot-scope="{ row }">
                <span>{{ row.checkAmount }}</span>
                <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-input  v-model="row.checkAmount"  prefix-icon="el-icon-_rmb" disabled />
                </el-form-item> -->
              </template>
            </el-table-column>
            <el-table-column label="差异金额" align="center" prop="diffAmount" sortable width="120">
              <template slot-scope="{ row }">
                <span>{{ row.diffAmount }}</span>
                <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-input  v-model="row.diffAmount"  prefix-icon="el-icon-_rmb" disabled />
                </el-form-item> -->
              </template>
            </el-table-column>
            <!-- <el-table-column label="供应商" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-select  filterable disabled v-model="row.supplierId" class="ele-fluid" >
                    <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column label="行备注" align="center" width="250">
              <template slot-scope="{ row }">
                  <el-input  v-model="row.remarks" placeholder="请输入行备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3" fixed='right'>
              <template slot-scope="{ row , $index}">
                <span class="ele-action">
                  <el-link  v-permission="'Inventory_Checkorder_ProductDel'"  icon="el-icon-delete" type="danger"   :underline="false" @click="remove(row, $index)" >删除</el-link>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card shadow="never"> </el-card>
        <!-- 底部工具栏 -->
        <div class="ele-bottom-tool">
          <div class="ele-bottom-tool-actions">
            <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" v-permission="'Inventory_Checkorder_Save'"  >
              挂单
            </el-button>
            <el-button type="warning" v-show="this.btnIndex!=3 && form.status!=5" :loading="loadingAudit" @click="audit" v-permission="'Inventory_Checkorder_Audit'"  >
              审核
            </el-button>
            <el-button type="danger" v-show="form.status==5"  @click="unAudit"   :loading="loadingUnAudit" v-permission="'Inventory_Checkorder_UnAudit'"  >
              反审核
            </el-button>
            <el-button @click="handleClose" >关闭</el-button>
          </div>
        </div>
      </el-form>
      <!-- <div class="ele-dailog-bottom" >
          <div class="left"  style="display: flex;width: 50%;">
          </div>
          <div class="right" style="display: flex;width: 32%;">
            <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" >
              挂单
            </el-button>
            <el-button type="warning" v-show="this.btnIndex!=3 && form.status!=5" :loading="loading" @click="audit">
              审核
            </el-button>
            <el-button type="danger" v-show="form.status==5"  @click="unAudit"   >
              反审核
            </el-button>
            <el-button @click="handleClose" >关闭</el-button>
          
          </div>
        </div> -->
     
      <!-- 编辑弹窗 -->
      <purchooseList :data="current" :visible.sync="showProductList"  @callback="reloadItemList"/>
    </div>
  </template>
  <script>
   
   import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';
   import purchooseList from '../components/purchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier } from '@/api/basicdatamanager/supplier';
   import { AddCheckorder, UpdateCheckorder,QueryCheckorderById,AuitCheckorder,AnitCheckorder } from '@/api/inventory/checkorder';



    export default {
      name: 'CheckOrderEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {purchooseList},
      data() {
        return {
          fixedHeight:true,
          // 表单数据
          form: {createUser:'',createDate:'',items:[]},
          // 表单验证规则
          rules: {
            wareHouseId: [{required: true,message: '请选择盘点仓库',trigger: 'blur'}],
            checkTypeId: [{required: true,message: '请选择盘点类型',trigger: 'blur'}],
            // supplierId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
            // contractNumber: [{required: true,message: '请输入合同号',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            costPrice:[{required: true,message: '请输入成本单价',trigger: 'blur'}],
          },
          current:null,
          isShow:false,
          // 提交状态
          loading: false,
          loadingAudit: false,
          loadingUnAudit: false,
          // 是否是修改
          isUpdate: 1,
          checkorderId:'',
          showProductList:false,
          defaultDate:new Date(),
          checkTypeDicts:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 380px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 280px)' : null;
          return fh;
        },
      },
      //初始化数据
      mounted(){
        if(this.isUpdate == 2 || this.isUpdate == 3){
          this.setData(this.checkorderId);
        }else if(this.isUpdate == 1){
          this.$refs['form'].clearValidate();
          this.form={items:[]};
          this.isUpdate = 1;
          let currentUser = getUser();
          this.$set(this.form,'createDate',this.defaultDate);
          this.$set(this.form,'createUser',currentUser.accountId);
        }
      },
      created(){
        this.initData();
        this.isUpdate = this.$route.query.isUpdate;
        this.checkorderId = this.$route.query.checkorderId;
        if(this.isUpdate == 1)  setPageTabTitle('添加盘点单');
        if(this.isUpdate == 2)  setPageTabTitle('修改盘点单');
        if(this.isUpdate == 3)  setPageTabTitle('查看盘点单');
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_PDLX).then((data)=>{
            this.checkTypeDicts = [];
            this.checkTypeDicts = data;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            this.loading = true;
            const saveOrUpdate = this.isUpdate == 2 ? UpdateCheckorder : AddCheckorder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible();
               
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 审核入库单 */
        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}


            if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

            this.loadingAudit = true;
            AuitCheckorder(this.form)
              .then((msg) => {
                this.loadingAudit = false;
                this.$message.success(msg);
                this.updateVisible();
              })
              .catch((e) => {
                this.loadingAudit = false;
                this.$message.error(e.message);
              });
          });
        },

        unAudit(){
          this.loadingUnAudit = true;
          AnitCheckorder(this.form.id)
            .then((msg) => {
              this.loadingUnAudit = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loadingUnAudit = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          QueryCheckorderById(id)
            .then((res) => {
              this.form = res; 

              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
          });
          
        },

        OpenProductList(){
          if(this.form.wareHouseId){
            this.showProductList =true;
            this.current = this.form;
          }else{
            this.$message.info("请选择盘点仓库")
          }
        },

        reloadItemList(orderData){

          this.form.items = [];
          orderData.map((item)=>{
            this.form.items.push({
              checkId:this.form.id,
              stockQty:item.stockQty,
              checkQty:item.stockQty,
              diffQty:0,
              checkAmount:(item.costPrice * item.stockQty).toFixed(4),
              diffAmount:0,
              stockAmount:(item.costPrice * item.stockQty).toFixed(4),
              stockId:item.id,
              costPrice:item.costPrice,
              purSharePrice:item.purSharePrice,
              inSharePrice:item.inSharePrice,
              billDetailId:item.billDetailId,
              stockItemId:item.stockItemId,
              unitId:item.unitId,
              productId:item.productId,
              productCode:item.productCode,
              productName:item.productName,
              spc:item.spc,
              unitDesc:item.unitDesc,
              supplierId:item.supplierId,
            })
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          this.setPurAmountTotal();
        },

        //设置金额
        setAmount(row,index){

          console.log('setAmount row',row);
          this.$refs.items.data[index].diffQty = row.checkQty -row.stockQty

          if(row.costPrice && row.checkQty){
              let cq = parseFloat(row.checkQty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].checkAmount = (cp * cq).toFixed(2);
          }

          if(row.costPrice && row.diffQty){
              let dq = parseFloat(row.diffQty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].diffAmount = (cp * dq).toFixed(2);
          }

          this.setPurAmountTotal();
        },


        //设置入库金额
        setPurAmountTotal(){
          
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){

            let ssa = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.stockAmount) },0);
            let sca = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.checkAmount) },0);
            let sda = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.diffAmount) },0);

            let stockQtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.stockQty) },0);
            let checkQtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.checkQty) },0);
            let diffQtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.diffQty) },0);

            this.$set(this.form,'sumCheckAmount',sca.toFixed(4))
            this.$set(this.form,'sumStockAmount',ssa.toFixed(4))
            this.$set(this.form,'sumDiffAmount',sda.toFixed(4))

            this.$set(this.form,'stockQtyTotal',stockQtyTotal.toFixed(2))
            this.$set(this.form,'checkQtyTotal',checkQtyTotal.toFixed(2))
            this.$set(this.form,'diffQtyTotal',diffQtyTotal.toFixed(2))
          }
        },

        /* 删除 */
        remove(_row, index) {

          
          this.form.items = this.form.items.filter((c)=>{return c.productCode !=_row.productCode && c.productName != _row.productName});
          // this.form.items.splice(index, 1);
          this.setPurAmountTotal();
        },
     
        /* 更新visible */
        updateVisible() {
          removePageTab({ key: this.$route.path });
          reloadPageTab({ fullPath: '/invoicingmanager/checkordermanager' });
        },

        handleClose() {
          removePageTab({ key: this.$route.path });
          this.$router.push('/invoicingmanager/checkordermanager');
        },

        /* 合计 */
        getSummaries(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==5){
              sums[index] = Number(this.form.stockQtyTotal).toFixed(2);
            }else if(index ==6){
              sums[index] = Number(this.form.checkQtyTotal).toFixed(4);
            }else if(index ==7){
              sums[index] = Number(this.form.diffQtyTotal).toFixed(4);
            }else if(index ==9){
              sums[index] = Number(this.form.sumStockAmount).toFixed(4);
            }else if(index ==10){
              sums[index] = Number(this.form.sumCheckAmount).toFixed(4);
            }else if(index ==11){
              sums[index] = Number(this.form.sumDiffAmount).toFixed(4);
            }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          return sums;
        },

        /* 样式 */
        cellStyle(param){
          const { row, column, rowIndex, columnIndex } = param;
          if(columnIndex==5||columnIndex==6||columnIndex==7||columnIndex==9||columnIndex==10||columnIndex==11){
            return{
              color:''
            }
          }
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={};
              this.isUpdate = false;

              let currentUser = getUser();
              this.$set(this.form,'createDate',this.defaultDate);
              this.$set(this.form,'createUser',currentUser.accountId);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
              let currentUser = getUser();
              this.$set(this.form,'createDate',this.defaultDate);
              this.$set(this.form,'createUser',currentUser.accountId);
          }
        }
      }
    };
  </script>
  <style lang="scss" scoped>
  /*总计字体颜色
  ::v-deep .el-table__footer-wrapper tbody td {
     color: var(--color-primary);
     cursor: pointer;
   }*/
 </style>